<template>
  <el-dialog
    :title="isEdit?'编辑房产':'添加房产'"
    :visible="visible"
    :close-on-click-modal="false"
    top="5vh"
    width="70%"
    @close="closeFn"
  >
    <el-form
      ref="form"
      :model="form"
      label-width="70px"
      :rules="rules"
      style="padding-right:30px"
    >
      <el-form-item label="经纪" prop="agent">
        <el-select v-model="form.agent" placeholder="请选择经纪">
          <el-option v-for="item in agentList" :key="item.id" :value="item.id" :label="item.name" />
        </el-select>
      </el-form-item>
      <el-form-item label="分类" prop="category">
        <el-select v-model="form.category" placeholder="请选择分类">
          <el-option v-for="item in categoryList" :key="item.id" :value="item.id" :label="item.title" />
        </el-select>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" autocomplete="off" />
      </el-form-item>
      <el-form-item label="标签" prop="tags">
        <el-tag
          v-for="(tag, index) in form.tags"
          :key="tag"
          closable
          :disable-transitions="false"
          class="form-tags"
          @close="form.tags.splice(index,1)"
        >
          {{ tag }}
        </el-tag>
        <el-input
          v-if="showingTagInput"
          ref="saveTagInput"
          v-model="inputNewTag"
          class="input-new-tag"
          size="small"
          @keyup.enter.native="saveTagInput"
          @blur="saveTagInput"
        />
        <el-button v-else class="button-new-tag" size="small" @click="showTagInput">+ 新标签</el-button>
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-row type="flex" :gutter="10">
          <el-col :span="6">
            <districtSelection ref="address" @change="addressChanged" />
          </el-col>
          <el-col :span="18">
            <el-input v-model="form.address" width="100%" />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input v-model="form.price" autocomplete="off" />
      </el-form-item>
      <el-form-item label="描述" prop="desc">
        <el-input v-model="form.desc" type="textarea" :rows="3" resize="none" autocomplete="off" />
      </el-form-item>
      <el-form-item label="内容">
        <VueEditor ref="vueEditor" :config="vueEditorConfig" />
      </el-form-item>
      <el-form-item label="介绍图片">
        <uploadImage ref="photos" :show-list="true" />
      </el-form-item>
      <el-form-item label="封面">
        <uploadImage ref="cover" />
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="$emit('update:visible', false)">取 消</el-button>
      <el-button type="primary" @click="confirm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>

import VueEditor from 'vue-word-editor'
import 'quill/dist/quill.snow.css'
import { addProperty, editProperty, getPropertyDetailByID } from '@/api/realEstate'
import { typefix } from '@/utils/typefix'
export default {
  components: {
    VueEditor
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    agentList: {
      type: Array,
      required: true
    },
    categoryList: {
      type: Array,
      required: true
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      form: {},
      rules: {
        title: [
          { required: true, message: 'title is required' }
        ],
        desc: [
          { required: true, message: 'description is required' }
        ]
      },
      inputNewTag: '',
      showingTagInput: false,
      vueEditorConfig: {
        uploadImage: { },
        uploadVideo: { }
      }
    }
  },
  created() {
    this.initForm()
  },
  methods: {
    async confirm() {
      await this.$refs.form.validate()
      const photosFinished = !this.$refs.photos.fileList.find(item => item.status !== 'success')
      const coverFinished = !this.$refs.cover.fileList.find(item => item.status !== 'success')
      if (!photosFinished || !coverFinished) return this.$message.warning('请等待图片全部上传完成')
      this.form.content = this.$refs.vueEditor.editor.root.innerHTML
      this.form.image = this.$refs.cover.fileList[0]?.url || ''
      this.form.photos = this.$refs.photos.fileList.map(item => item.url)
      if (this.isEdit) {
        console.log('editing...', this.form)
        await editProperty(this.form)
        this.$message.success('编辑成功')
      } else {
        console.log('adding...', this.form)
        await addProperty(this.form)
        this.$message.success('添加成功')
      }
      this.$emit('update:visible', false)
      this.$emit('reload')
      this.initForm()
    },
    saveTagInput() {
      console.log('当前输入的值为', this.inputNewTag)
      if (this.form.tags.find(tag => tag === this.inputNewTag.trim())) {
        return this.$message.warning('输入的标签已存在')
      }
      if (this.inputNewTag.trim()) {
        this.form.tags.push(this.inputNewTag)
      }
      this.inputNewTag = ''
      this.showingTagInput = false
    },
    showTagInput() {
      this.showingTagInput = true
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async echo(id) {
      console.log('数据回显开始: id = ' + id)
      const { data } = await getPropertyDetailByID(id)
      console.log('原始数据：', data)
      this.form = {
        ...data,
        agent: data.agent?.id,
        category: data.category?.id,
        tags: typefix(data.tags, 'array'),
        image: typefix(data.image, 'string'),
        photos: typefix(data.photos, 'array')
      }
      this.$refs.address.echo(this.form.address?.split(', '))
      this.$refs.cover.fileList = this.form.image ? [{ url: this.form.image }] : []
      this.$refs.photos.fileList = this.form.photos.map(item => ({ url: item }))
      this.$refs.vueEditor.editor.root.innerHTML = this.form.content
      console.log('数据回显完成', this.form)
    },
    closeFn() {
      this.$emit('update:visible', false)
      this.initForm()
      this.$refs.vueEditor.editor.root.innerHTML = ''
      this.$refs.cover.fileList = []
      this.$refs.photos.fileList = []
      this.$refs.form.resetFields()
      this.$refs.address.echo([])
    },
    initForm() {
      this.form = {
        'title': '',
        'desc': '',
        'image': '',
        'agent': '',
        'content': '',
        'address': '',
        'price': '',
        'photos': [],
        'tags': [],
        'category': '',
        'created_by': '',
        'updated_by': ''
      }
    },
    addressChanged(val) {
      this.form.address = val
    }
  }
}
</script>
<style lang="scss" scoped>
.form-tags, .button-new-tag {
    margin: 0 3px;
}
.input-new-tag {
    width: 120px;
    margin: 0 3px;
}
</style>
